import { createElement, HTMLAttributes, useState, type FC } from 'react';
import classNames from 'classnames';
import { useEnsuredForwardedRef, useUpdateEffect } from 'react-use';
import { shapeSideDefaultProps } from './defaultProps';
import type { ShapeSideOptions } from './type';
import { useShapeContext } from './ShapeContext';

export interface ShapeSideProps extends ShapeSideOptions, HTMLAttributes<HTMLDivElement> {}

const ShapeSide: FC<ShapeSideProps> = (props) => {
  const { className, ui, active, index, children, forwardedRef, style, ...shapeSideProps } = props;
  const ensuredForwardRef = useEnsuredForwardedRef<HTMLDivElement>(forwardedRef!);
  const [states, setStates] = useShapeContext();
  const [styles, setStyles] = useState(style);
  const [hidden, setHidden] = useState(false);
  const [animating, setAnimating] = useState(false);
  const [isActive, setIsActive] = useState(active);

  useUpdateEffect(() => {
    if (states.animating) {
      if (active) {
        setHidden(true);
        setStyles({ ...style, transform: 'rotateY(0deg)', transitionDuration: `${states.duration}ms` });
      } else if (states.activeIndex === states.maxIndex ? index === 0 : index === states.activeIndex! + 1) {
        setAnimating(true);
        setStyles({
          ...style,
          left: 0,
          transform: 'rotateY(-90deg) translateZ(145px) translateX(-145px)',
          transitionDuration: `${states.duration}ms`,
        });
      }
      /* setTimeout(() => {
        setStates({
          ...states,
          activeIndex: states.activeIndex === states.maxIndex ? 0 : (states.activeIndex || 0) + 1,
        });
        if (index === (states.activeIndex === states.maxIndex ? 0 : (states.activeIndex || 0) + 1)) {
          setIsActive(true);
        }
      }, (states.duration || 0) + 30); */
    } else {
      if (active) {
        setIsActive(false);
      }

      console.log(states, index, '&&&&');

      setStates({
        ...states,
        activeIndex: states.activeIndex === states.maxIndex ? 0 : (states.activeIndex || 0) + 1,
      });

      if (index === (states.activeIndex === states.maxIndex ? 0 : (states.activeIndex || 0) + 1)) {
        setIsActive(true);
      }
      /* else if (states.activeIndex === states.maxIndex ? index === 0 : index === states.activeIndex! + 1) {
        setIsActive(true);
        setStates({ ...states, activeIndex: index });
      } */
      setHidden(false);
      setAnimating(false);
      setStyles(style);
    }
  }, [states.animating]);

  return createElement(
    'div',
    {
      ref: ensuredForwardRef,
      className: classNames({ ui, active: isActive, hidden, animating }, 'side', className),
      style: styles,
      ...shapeSideProps,
    },
    children,
  );
};

ShapeSide.displayName = 'ShapeSide';
ShapeSide.defaultProps = shapeSideDefaultProps;

export default ShapeSide;
